<!--
 * @Descripttion: 人员管理
 * @LastEditors: xzh
 * @LastEditTime: 2023-09-14 15:58:04
-->
<template>
  <Splitpanes class="default-theme">
    <!-- 文件夹树 -->
    <Pane size="15" min-size="15">
      <el-tree
        node-key="id"
        ref="departTreeRef"
        class="dile-tree"
        v-loading="personmentParam.treeLoading"
        :data="personmentParam.treeData"
        :props="personmentParam.treeProps"
        :expand-on-click-node="false"
        @node-click="handleNodeCick"
      />
    </Pane>
    <!-- 表格 -->
    <Pane min-size="40">
      <el-card>
        <DileTable ref="dileTableRef">
          <template #preColumn>
            <vxe-column
              field="name"
              :title="$t('page.organizeManageArr.personArr.name')"
            />
            <vxe-column
              field="code"
              :title="$t('page.organizeManageArr.personArr.jobNumber')"
            />
            <vxe-column
              field="account"
              :title="$t('page.organizeManageArr.personArr.account')"
            />
            <vxe-column
              field="sex"
              :title="$t('page.organizeManageArr.personArr.sex')"
            />
            <vxe-column
              :title="$t('page.organizeManageArr.departmentArr.department')"
            >
              <template #default="{ row }">
                <span>{{ row.extJson?.departmentName }}</span>
              </template>
            </vxe-column>
            <vxe-column :title="$t('page.organizeManageArr.postmentArr.post')">
              <template #default="{ row }">
                <span>{{ row.extJson?.jobPostName }}</span>
              </template>
            </vxe-column>
            <vxe-column
              field="telephone"
              :title="$t('page.organizeManageArr.personArr.telephone')"
            />
            <vxe-column
              field="emailAddress"
              :title="$t('page.organizeManageArr.personArr.emailAddress')"
            />
            <vxe-column field="status" :title="$t('common.status')">
              <template #default="{ row }">
                <span>{{
                  !!row.status
                    ? $t("table.btnArr.enable")
                    : $t("table.btnArr.disEnable")
                }}</span>
              </template>
            </vxe-column>
          </template>
        </DileTable>
      </el-card>
    </Pane>
    <!-- 人员表单 -->
    <PersonFrom ref="personFromRef" @refresh="initTableData" />
  </Splitpanes>
</template>

<script setup lang="ts">
import { ref, reactive, provide, onMounted, nextTick } from "vue";
import type { propsParam_Inf } from "@/components/dile-table/index.type";
import type { object_Inf } from "@/utils/typings/index.type";
import { useI18n } from "vue-i18n";
import { ElNotification, ElMessageBox } from "element-plus";
import { Splitpanes, Pane } from "splitpanes";
import { organizeModuleToolEnum } from "@/utils/typings/organizeManage/index.type";
import DileTable from "@/components/dile-table/index.vue";
import PersonFrom from "./person-form/index.vue";
import Dile_APi from "@/api";
import Dile_Methods from "@/utils/methods";

/**
 * @Author: xzh
 * @Descripttion:i18n实例
 * @Param:
 */
let { t } = useI18n();

/**
 * @Author: xzh
 * @Descripttion: 人员表单实例
 * @Param:
 */
let personFromRef = ref<any>(null);
/**
 * @Author: xzh
 * @Descripttion: 部门树实例
 * @Param:
 */
let departTreeRef = ref<any>(null);
/**
 * @Author: xzh
 * @Descripttion: 表格实例
 * @Param:
 */
let dileTableRef = ref<any>(null);

/**
 * @Author: xzh
 * @Descripttion: 人员管理参数
 * @Param:
 */
let personmentParam = reactive<object_Inf>({
  treeLoading: false,
  selectNode: {
    id: 0,
  },
  treeData: [],
  treeProps: {
    children: "children",
    label: "name",
    value: "id",
  },
});
provide("personmentParam", personmentParam);

/**
 * @Author: xzh
 * @Descripttion:初始化加载
 * @Param:
 */
onMounted(() => {
  initDepartTree();
  // initTableData();
});

/**
 * @Author: xzh
 * @Descripttion: 加载部门tree
 * @Param:
 */
let initDepartTree = async () => {
  try {
    personmentParam.treeLoading = true;
    //获取部门信息
    let departData = await Dile_APi.getDepartmentList();
    //格式化成树
    let { treeData, firstChildNode } = Dile_Methods.formatToTree(departData);

    Object.assign(personmentParam, {
      selectNode: firstChildNode,
      treeData,
    });
    await nextTick();
    //设置选中
    departTreeRef.value.setCurrentNode(firstChildNode);
    //加载表格事件
    initTableData();
  } finally {
    personmentParam.treeLoading = false;
  }
};

/**
 * @Author: xzh
 * @Descripttion: 节点点击事件
 * @Param:
 * @param {*} node
 */
let handleNodeCick = (node: object_Inf) => {
  personmentParam.selectNode = node;
  //加载表格事件
  initTableData();
};
/**
 * @Author: xzh
 * @Descripttion:加载表格事件
 * @Param:
 */
let initTableData = async () => {
  try {
    propsParam.loading = true;
    Object.assign(propsParam, {
      tableData: [],
      loading: true,
    });
    let { keyWord, pagination } = dileTableRef.value?.getTableParam(),
      { id: orgId } = personmentParam.selectNode,
      { page, rows } = pagination;
    //获取人员列表
    let { record: tableData, total } = await Dile_APi.getUserList({
      keyWord,
      orgId,
      pagination: {
        pageIndex: page,
        pageSize: rows,
      },
    });
    Object.assign(propsParam, {
      tableData,
      tableRecords: total,
    });
  } finally {
    propsParam.loading = false;
  }
};
/**
 * @Author: xzh
 * @Descripttion:工具栏按钮点击事件
 * @Param:
 * @param {*} event
 */
let handleToolBtnClick = (event: object_Inf) => {
  let { code } = event,
    { rowChecked } = dileTableRef.value;
  //![新增]->行勾选判断
  if (!["add"].includes(code) && !rowChecked()) {
    return false;
  }
  switch (code) {
    case "add":
    case "edit":
      //加载人员抽屉
      InitPersonDrawer(code);
      break;
    case "delete":
      //删除
      handleDelete();
      break;
    case "enable":
    case "disEnable":
      //启用&&停用
      handleUpdateStatus(code);
      break;
    case "resetPassWord":
      //重置密码
      handleResetPassWord();
      break;
  }
};

/**
 * @Author: xzh
 * @Descripttion:加载人员抽屉
 * @Param:
 * @param {*} code
 */
let InitPersonDrawer = (code: string) => {
  let { clearCheckboxRow, getTableParam } = dileTableRef.value,
    { selectObjArr } = getTableParam(),
    currentRow = selectObjArr?.find(() => true);
  //加载抽屉
  personFromRef.value.init(code == "edit" ? currentRow.id : 0);
  //清楚行选中
  code == "edit" && clearCheckboxRow([currentRow]);
};

/**
 * @Author: xzh
 * @Descripttion: 删除事件
 * @Param:
 */
let handleDelete = () => {
  ElMessageBox.confirm(
    t("common.message.deleteVerify"),
    t("common.message.confirmInfo"),
    {
      distinguishCancelAndClose: true,
      type: "warning",
      confirmButtonText: t("common.define"),
      cancelButtonText: t("common.cancel"),
    }
  ).then(async () => {
    try {
      propsParam.loading = true;
      let { selectObjArr } = dileTableRef.value.getTableParam();
      //删除选中人员
      await Dile_APi.deleteUser(selectObjArr.map((x: object_Inf) => x.id));
      //提示成功
      ElNotification({
        message: t("common.message.OperationSuccess"),
        type: "success",
      });
      //刷新表格
      initTableData();
    } finally {
      propsParam.loading = false;
    }
  });
};
/**
 * @Author: xzh
 * @Descripttion: 修改状态
 * @Param:
 * @param {*} code
 */
let handleUpdateStatus = async (code: string) => {
  try {
    propsParam.loading = true;
    let { selectObjArr } = dileTableRef.value.getTableParam(),
      ids: Array<string> = selectObjArr.map((x: object_Inf) => x.id),
      //修改状态
      updateSatus = code == "enable";
    //更新人员状态
    await Dile_APi.updateUserStatus(ids, updateSatus);
    //提示成功
    ElNotification({
      message: t("common.message.OperationSuccess"),
      type: "success",
    });
    //修改行状态
    (propsParam.tableData || [])
      .filter((x) => ids.includes(x.id))
      .forEach((row) => (row.status = updateSatus));
  } finally {
    propsParam.loading = false;
  }
};

/**
 * @Author: xzh
 * @Descripttion: 重置密码
 * @Param:
 * @param {*} code
 */
let handleResetPassWord = async () => {
  let { selectObjArr } = dileTableRef.value.getTableParam(),
    ids: Array<string> = selectObjArr.map((x: object_Inf) => x.id);
  //重置密码
  await Dile_APi.resetPassword(ids);
  //提示成功
  ElNotification({
    message: t("common.message.OperationSuccess"),
    type: "success",
  });
};

/**
 * @Author: xzh
 * @Descripttion: 表格参数
 * @Param:
 */
let propsParam = reactive<propsParam_Inf>({
  moduleToolCode: organizeModuleToolEnum.personment,
  loading: false,
  checkbox: true,
  tableData: [],
  isPagination: true,
  emitEvents: {
    refreshTable: initTableData,
    toolBtnClick: handleToolBtnClick,
  },
});
provide("propsParam", propsParam);
</script>
<style lang="scss" scoped></style>
